package cn.zn.modules.zzsys.cur.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.zn.framework.common.utils.PageUtils;
import cn.zn.modules.zzsys.cur.entity.vo.WappReqUserVo;
import cn.zn.modules.zzsys.cur.service.WappService;
import cn.zn.modules.zzsys.cur.dao.WappDao;
import cn.zn.modules.zzsys.cur.entity.BasisWappEntity;
import cn.zn.modules.zzsys.inter.WappInter;
import cn.zn.modules.zzsys.inter.vo.WappVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service("wappService")
public class WappServiceImpl extends ServiceImpl<WappDao, BasisWappEntity> implements WappService, WappInter {

    @Override
    public PageUtils queryPage(BasisWappEntity wapp, IPage<BasisWappEntity> page) {

        QueryWrapper<BasisWappEntity> wappQueryWrapper = Wrappers.query();

        IPage<BasisWappEntity> pageResult = this.page(page, wappQueryWrapper);
        return new PageUtils(pageResult);
    }

    @Override
    @Transactional
    public BasisWappEntity login(WappReqUserVo wappReqUserVo, WxMaJscode2SessionResult wxMaJscode2SessionResult) {
        /**
         * 注册微信用户
         */
        QueryWrapper<BasisWappEntity> sysWappEntityQueryWrapper = Wrappers.query();
        sysWappEntityQueryWrapper.eq("open_id", wxMaJscode2SessionResult.getOpenid());
        BasisWappEntity wappEntity = this.getOne(sysWappEntityQueryWrapper);
        if (wappEntity == null) {
            // 微信信息
            wappEntity = new BasisWappEntity();
            BeanUtils.copyProperties(wappReqUserVo, wappEntity);
            wappEntity.setOpenId(wxMaJscode2SessionResult.getOpenid());
            wappEntity.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
            super.save(wappEntity);
        }
        return wappEntity;
    }

    @Override
    public List<WappVO> listByIds(List<Long> ids) {
        return super.listByIds(ids).stream().map(o -> {
            WappVO wappVO = new WappVO();
            BeanUtils.copyProperties(o, wappVO);
            return wappVO;
        }).collect(Collectors.toList());
    }
}